<!--
   Copyright 2020-2021 the original author or authors.

   Licensed under the General Public License, Version 3.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

        https://www.gnu.org/licenses/gpl-3.0.en.html
 -->

<template>
    <div class="box clearfix" v-if="apply">
      <div class="title">
        <span>Welcome to ZZUOJ</span>
      </div>
      <div class="body">
        <Form
          ref="registerForm"
          :model="registerForm"
          :rules="registerRules"
          label-position="right"
          :label-width="105"
          label-colon>
          <FormItem prop="username" label="用户名">
            <Input
              v-model="registerForm.username"
              placeholder="用于您的账户登录"
            />
          </FormItem>
          <FormItem prop="email" label="邮箱">
            <Input v-model="registerForm.email"
                   placeholder="填写未注册过的邮箱" type="email"/>
          </FormItem>
          <FormItem prop="password" label="密码">
            <Input
              v-model="registerForm.password"
              placeholder="长度至少为六个字符"
              type="password"
            />
          </FormItem>
          <FormItem prop="confirmPassword" label="确认密码">
            <Input
              v-model="registerForm.confirmPassword"
              placeholder="与输入密码一致"
              type="password"
            />
          </FormItem>
          <FormItem label="学号">
            <Input v-model="registerForm.studentId"
                   placeholder="郑州大学学号"
            />
          </FormItem>
          <FormItem prop="captcha" label="验证码">
            <div class="captcha-code">
              <Input
                v-model="registerForm.captcha"
                placeholder="Click to get captcha"
                @on-focus="onCaptchaInputFocus"
              />
            </div>
            <div class="captcha-img">
              <Tooltip content="Click to refresh" placement="right">
                <img :src="captchaImg" @click="getCaptcha"/>
              </Tooltip>
            </div>
        </FormItem>
        </Form>
      </div>
      <div class="bottom">
        <div class="btns">
          <router-link :to="{ name: 'login' }">已经注册过</router-link>
          <Button type="text"
            @click="handleRegister('registerForm')"
            :loading="btnRegisterLoading">确认注册</Button>
        </div>
      </div>
    </div>
    <div class="container activation hover" v-else>
      <Tooltip  content="Return to Home" placement="bottom">
        <Icon type="md-checkmark-circle-outline" size="30"/>
        <h1 style="display: inline" @click="$router.replace({ name: 'home' })">&nbsp; {{ message }}</h1>
      </Tooltip>
    </div>
</template>

<script>
import api from '_u/api';

export default {
  // 打开 register 页面的时候，默认调我的接口 "get验证码"，然后我把一个验证码ID，和验证码图片Base64 给你
  data: function () {
    const validateUsername = (rule, value, callback) => {
      // 检查用户名是否存在
      api.isExist({ username: value }).then(ret => {
        callback();
      }, _ => {
        callback(new Error('该用户名已存在'));
      });
    };
    const validateEmail = (rule, value, callback) => {
      // 检查邮箱是否已被使用
      api.isExist({ email: value }).then(ret => {
        callback();
      }, _ => {
        callback(new Error('该邮箱已经被注册过'));
      });
    };
    const validatePass = (rule, value, callback) => {
      if (value !== '') {
        this.$refs.registerForm.validateField('confirmPassword');
      }
      callback();
    };
    const validateConfirmPass = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('密码不匹配'));
      }
      callback();
    };
    return {
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        studentId: '',
        captcha: ''
      },
      registerRules: {
        username: [
          { required: true, trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        email: [
          { required: true, type: 'email', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', min: 6, max: 32 },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPass, trigger: 'change' }
        ],
        captcha: [{ required: true, trigger: 'blur', min: 1, max: 10 }]
      },
      captchaId: 0,
      captchaImg: '',
      btnRegisterLoading: false,
      apply: true,
      message: ''
    };
  },
  methods: {
    getCaptcha: function() {
      // 模拟获得图形验证码
      api.getCaptcha().then(ret => {
        this.captchaId = ret.captchaId;
        this.captchaImg = ret.captcha;
      });
    },
    onCaptchaInputFocus: function() {
      if (!this.captchaId) {
        this.getCaptcha();
      }
    },
    handleRegister: function (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          const dataForm = Object.assign({}, this.registerForm);
          delete dataForm.confirmPassword;
          dataForm.captchaId = this.captchaId;
          this.btnRegisterLoading = true;
          api.register(dataForm).then(ret => {
            this.apply = false;
            this.message = '查收邮箱查看验证码：Success, check your email for activation';
            this.$refs[name].resetFields();
          }).catch(err => {
            this.$Message.error(err.message);
            this.btnRegisterLoading = false;
          }).finally(() => {
            this.registerForm.captcha = '';
            this.getCaptcha();
          })
          return;
        }
        this.registerForm.captcha = '';
      });
    }
  },
  mounted: function() {
    if (this.$route.query.token) {
      api.verifyEmail(this.$route.query.token)
        .then(_ => {
          this.apply = false;
          this.message = '已经发送过邮箱：You have activated';
        }).catch(err => {
          this.$Message.error(err.message);
        });
    }
  }
};
</script>

<style lang="less" scoped>
.box {
  width: 400px;
  padding: 20px;
  margin: 30px auto 0;
  background-color: #fff;
  border-radius: 5px;
}

.title {
  margin-bottom: 20px;
  text-align: center;
  color: #22aa55;
  font-size: 24px;
  font-weight: bold;
}

.box-main {
  padding: 10px;
}

/deep/.ivu-form-item-content {
  margin: 0;
}
/deep/ .ivu-input.ivu-input-default {
  width: 220px;
}

.btns {
  width: 50%;
  margin: 10px auto;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .ivu-btn:hover {
    background: rgba(0, 0, 0, 0.05);
  }
  a {
    color: #000;
    text-decoration: underline;
    margin-right: 8px;
  }
}

.captcha-img {
  margin-top: 5px;
}

.bottom {

}

.activation {
  text-align: center;
}
</style>
